#!/bin/bash
# 一键解决401错误脚本
# 专门针对zmyzmy.xin服务器的Flask JWT问题

echo "🚨 开始一键修复Flask JWT 401错误"
echo "=================================="

SECRET_KEY="aqm-jwt-secret-1749456354171-rLD9xAdYFvBlNXa8vop3Um9zJ6l9V8qDSkhBbzVwVbCsHKvOaNsWiFmi34VpNlDD"

echo "1️⃣ 强制终止所有Flask进程..."
pkill -9 -f python 2>/dev/null || true
pkill -9 -f flask 2>/dev/null || true
sleep 3

echo "2️⃣ 清理缓存文件..."
find /www/wwwroot/flask-auth -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
find /www/wwwroot/flask-auth -name "*.pyc" -delete 2>/dev/null || true

echo "3️⃣ 备份并修改配置文件..."
cd /www/wwwroot/flask-auth
cp app/config.py app/config.py.oneclick_backup

# 直接硬编码SECRET_KEY（最可靠的方法）
sed -i "s/SECRET_KEY = os.getenv('SECRET_KEY'.*)/SECRET_KEY = '$SECRET_KEY'/g" app/config.py

# 验证修改是否成功
if grep -q "$SECRET_KEY" app/config.py; then
    echo "✅ SECRET_KEY已成功硬编码"
else
    echo "⚠️ 使用Python脚本修改..."
    python3 -c "
import re
with open('app/config.py', 'r') as f:
    content = f.read()
content = re.sub(r'SECRET_KEY = os\.getenv\([^)]+\)', \"SECRET_KEY = '$SECRET_KEY'\", content)
with open('app/config.py', 'w') as f:
    f.write(content)
print('SECRET_KEY已硬编码')
"
fi

echo "4️⃣ 创建环境变量文件..."
echo "SECRET_KEY=$SECRET_KEY" > .env

echo "5️⃣ 重新启动Flask应用..."
export SECRET_KEY="$SECRET_KEY"
nohup python3 run.py > /tmp/oneclick_fix.log 2>&1 &

echo "6️⃣ 等待应用启动..."
sleep 8

echo "7️⃣ 测试修复结果..."

# 测试基础连接
if curl -s -f http://localhost:5000/api/auth/test > /dev/null; then
    echo "✅ Flask应用已启动"
    
    # 测试登录和JWT验证
    login_result=$(curl -s -X POST -H "Content-Type: application/json" \
        -d '{"username":"admin","password":"admin"}' \
        http://localhost:5000/auth/login)
    
    if echo "$login_result" | grep -q "access_token\|token"; then
        echo "✅ 登录成功"
        
        # 提取token并测试API访问
        token=$(echo "$login_result" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    token = data.get('access_token') or data.get('data', {}).get('token', '')
    print(token)
except:
    pass
")
        
        if [ ! -z "$token" ]; then
            api_result=$(curl -s -H "Authorization: Bearer $token" \
                http://localhost:5000/dashboard/overview)
            
            if echo "$api_result" | grep -v "401\|Unauthorized" > /dev/null; then
                echo ""
                echo "🎉🎉🎉 修复成功！JWT认证问题已完全解决！ 🎉🎉🎉"
                echo ""
                echo "✅ 所有API现在可以正常访问"
                echo "✅ 401错误已消除"
                echo "✅ Dashboard功能已恢复"
                echo ""
                echo "📝 修复摘要："
                echo "   - 使用硬编码SECRET_KEY: $SECRET_KEY"
                echo "   - 清理了进程和缓存"
                echo "   - Flask应用已重新启动"
                echo ""
                echo "🌐 现在可以正常使用前端应用了！"
                exit 0
            else
                echo "❌ API访问仍然返回401错误"
            fi
        else
            echo "❌ 无法提取token"
        fi
    else
        echo "❌ 登录失败"
    fi
else
    echo "❌ Flask应用启动失败"
fi

echo ""
echo "❌ 一键修复未完全成功，但不要担心！"
echo ""
echo "🔧 请尝试以下补救措施："
echo ""
echo "方法A - 手动重启："
echo "   pkill -9 -f python"
echo "   cd /www/wwwroot/flask-auth"
echo "   python3 run.py"
echo ""
echo "方法B - 检查进程："
echo "   ps aux | grep python"
echo "   netstat -tlnp | grep 5000"
echo ""
echo "方法C - 查看日志："
echo "   tail -f /tmp/oneclick_fix.log"
echo ""
echo "📞 如需进一步帮助，请查看生成的日志文件。"

exit 1
